package top.yqingyu.trans$client.common;

import top.yqingyu.qymsg.MsgHelper;
import top.yqingyu.qymsg.QyMsg;
import top.yqingyu.trans$client.main.TransClient;

import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.*;

/**
 * @author YYJ
 * @version 1.0.0
 * @ClassName top.yqingyu.transclient.main.TransSocket
 * @description
 * @createTime 2022年07月23日 23:46:00
 */
public class TransSocket implements Callable<Socket> {

    private final String host;
    private final int port;

    private final TransClient client;

    private TransSocket(String host, int port, TransClient client) {
        this.host = host;
        this.port = port;
        this.client = client;
    }

    public static Socket getTransSocket(TransClient client, String host, int port) throws ExecutionException, InterruptedException, TimeoutException, SocketException {

        FutureTask<Socket> socketFutureTask = new FutureTask<Socket>(new TransSocket(host, port, client));
        new Thread(socketFutureTask).start();
        return socketFutureTask.get(3, TimeUnit.SECONDS);
    }

    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    @Override
    public Socket call() throws Exception {
        Socket socket = new Socket(host, port);
        QyMsg clone = client.clientConf.AC_MSG.clone();
        clone.putMsg(client.clientConf.AC_STR);

        client.clientConf.msgTransfer.writeMessage(socket, clone);

        clone = client.clientConf.NORMAL_MSG.clone();
        clone.putMsg("trans ready");
        client.clientConf.msgTransfer.writeMessage(socket, clone);

        QyMsg msg = client.clientConf.msgTransfer.readMsg(socket, client.clientConf.MSG_TIMEOUT);

        String s = MsgHelper.gainMsg(msg);
        if ("ok".equals(s))
            return socket;
        return null;
    }
}
